<?php
namespace app\common\model;

use hema\event\Order as Ev;
use think\facade\Db;
use hema\wechat\Pay as WxPay;
use hema\delivery\Driver as Delivery;

/**
 * 公众号模型
 */
class Order extends BaseModel
{
    // 定义表名
    protected $name = 'order';

    // 定义主键
    protected $pk = 'order_id';

    // 追加字段
    protected $append = [
        'user'    
    ];

    /**
     * 模型基类初始化
     */
    public static function init()
    {
        parent::init();
        (new Ev((int)self::$applet_id))->listen();
    }

    /**
     * 订单商品列表
     */
    public function goods()
    {
        return $this->hasMany('app\\common\\model\\OrderGoods');
    }

    /**
     * 关联订单收货地址表
     */
    public function address()
    {
        return $this->hasOne('app\\common\\model\\OrderAddress');
    }

    /**
     * 关联订单配送表
     */
    public function delivery()
    {
        return $this->hasOne('app\\common\\model\\OrderDelivery');
    }

    /**
     * 关联评论表
     */
    public function comment()
    {
        return $this->hasOne('app\\common\\model\\Comment');
    }
    
    /**
     * 关联餐桌/包间表
     */
    public function table()
    {
        return $this->belongsTo('app\\common\\model\\Table');
    }
    
    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\Shop');
    }

    /**
     * 格式化到店时间
     */
    public function getArriveTimeAttr($value)
    {
        return ['text' => date("Y-m-d H:i:s",$value), 'value' => $value];
    }
    
    /**
     * 用户表
     */
    public function getUserAttr($value,$data)
    {
        return User::withoutGlobalScope()->find($data['user_id']);
    }

    /**
     * 订单来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自助点单', 20 => '代客点单', 30 => '平台点单'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 订单类型
     */
    public function getOrderModeAttr($value)
    {
        $status = [10 => '堂食', 20 => '外卖', 30 => '自取'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 付款状态
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款', 30 => '后付款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 商家状态
     */
    public function getShopStatusAttr($value)
    {
        $status = [10 => '待接单', 20 => '已接单', 30 => '已接单'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 配送状态
     */
    public function getDeliveryStatusAttr($value)
    {
        $status = [10 => '待配送', 20 => '配送中', 30 => '已配送'];
        return ['text' => $status[$value], 'value' => $value];
    }
    

    /**
     * 收货状态
     */ 
    public function getReceiptStatusAttr($value)
    {
        $status = [10 => '待收货', 20 => '已收货'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 退款状态
     */ 
    public function getRefundStatusAttr($value)
    {
        $status = [10 => '待退款', 20 => '已退款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 订单状态
     */
    public function getOrderStatusAttr($value)
    {
        $status = [10 => '进行中', 20 => '被取消', 30 => '已完成', 40 => '退款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否评价
     */
    public function getIsCmtAttr($value)
    {
        $status = ['待评价', '已评价'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 按照分类获取单列表
     * $type 类别 all=所有 payment=待付款 comment=待评价 refund=退款/售后
     */
    public function getList(string $dataType='all', $shop_id = 0, $user_id = 0, string $search = '')
    {
        // 筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id; 
        $user_id > 0 && $filter['user_id'] = $user_id; 
        $model = $this->with(['goods.image','shop','table','comment','delivery'])->order(['order_id' => 'desc']);
        switch ((string)$dataType) {
            case 'all'; //全部
                break;
            case 'payment'; //待付款
                $filter['pay_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'collection'; //待收款
                $filter['pay_status'] = 30;
                $filter['order_status'] = 10;
                break;
            case 'shop';//待接单
                $model->where('pay_status','>',10);
                $filter['shop_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'delivery';//待配送
                $model->where('shop_status','>',10);
                $filter['delivery_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'receipt';//待收货
                $filter['pay_status'] = 20;
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 30;
                $filter['receipt_status'] = 10;
                break;
            case 'cancel';//被取消
                $filter['order_status'] = 20;
                break;
            case 'complete';//已完成
                $filter['order_status'] = 30;
                break;
            case 'comment';//待评价
                $filter['is_cmt'] = 0;
                $filter['order_status'] = 30;
                break;
            case 'refund';//全部退款
                $filter['order_status'] = 40;
                break;
            case 'refund10';//待退款
                $filter['refund_status'] = 10;
                $filter['order_status'] = 40;
                break;
            case 'refund20';//已退款
                $filter['refund_status'] = 20;
                $filter['order_status'] = 40;
                break;
        }
        return $model->where($filter)->paginate(['list_rows'=>15,'query' => request()->param()]); 
    }

    /**
     * 订单详情
     */
    public static function detail($id)
    {
        return self::with(['goods' => ['image', 'spec', 'goods'], 'address', 'shop', 'table','delivery'])
            ->where(['order_id' => $id])
            ->find();
    }

    /**
     * 商家接单
     */
    public function setShopStatus()
    {
        //发送商家接单订阅消息
        food_post_tpl('receive',$this->order_id);
        return $this->save([
            'shop_status' => 20,
            'shop_time' => time()
        ]);
    }

    /**
     * 确认收到用户付款（后付费用户）
     */
    public function collection()
    {
        // 开启事务
        Db::startTrans();
        try {
            //如果该用户存在则执行下列操作，代客非会员下单不会执行
            if($user = User::get($this->user_id)){
                $user->pay = ['inc', $this->pay_price];//增加消费金额
                $user->score = ['inc', $this->pay_price];//增加消费积分
                $user->save();
                //添加交易记录
                $record = new Record;
                $record->save([
                    'order_no' => $this->order_no,
                    'money' => $this->pay_price,
                    'user_id' => $this->user_id,
                    'shop_id' => $this->shop_id,
                    'applet_id' => $this->applet_id,
                    'type' => 20,//现金（默认）
                    'mode' => 20,//后台操作
                    'action' => 40,//消费
                    'remark' => '当面付款'
                ]);
            }
            $this->save(['pay_status' => 20,'pay_time' => time()]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    
     /**
     * 设置配送状态
     */
    public function setDeliveryStatus(array $data = [])
    {
        $delivery = [
            'delivery_status' => $data['delivery_status'],
            'delivery_time' => time()
        ];
        if($data['delivery_status'] == 40){
            food_post_tpl('delivery',$this->order_id);//骑手配送订阅消息
        }
        if($data['delivery_status'] == 50){
            $delivery['status'] = 30;
            $this->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return $this->delivery->save($delivery);
    }

    /**
     * 确认发货
     */
    public function setDelivery($company='', $shop_clerk_id='')
    {
        // 开启事务
        Db::startTrans();
        try {
            //外卖配送
            if($this->order_mode['value'] == 20){
                if($this->delivery_status['value']==10){
                    $data = [
                        'shop_status' => 30,//已推送外卖订单
                        'shop_time' => time(),
                        'delivery_status' => 20
                    ];
                    if($company == 'self'){
                        //是否开启骑手抢单
                        //if($this->shop['is_grab']['value'] == 0){
                            if(empty($shop_clerk_id)){
                                $clerk = ShopClerk::where(['shop_id' => $this->shop_id,'status' => 20])->find(); //获取店员信息
                            }else{
                                $clerk = ShopClerk::get($shop_clerk_id); //获取店员信息
                            }
                            $dev = [
                                'linkman' => $clerk['real_name'],
                                'phone' => $clerk['mobile'],
                                'delivery_status' => 30,  //已到店
                                'order_no' => $this->order_no,
                            ];
                            //骑手接单提醒
                            food_post_tpl('horseman',$this->order_id);
                        //}else{
                            //抢单通知
                            //sand_grab_msg($this);
                        //}
                    }
                    if($company == 'sf'){
                        $sf = new Delivery('sf',$this);;
                        if($result = $sf->addOrder()){
                            $real_pay_money = (int)$result['result']['real_pay_money'];//配送费
                            $real_pay_money = round($real_pay_money / 100,2); //四舍五入保留两位小数
                            $dev = [
                                'price' => $real_pay_money, //配送费
                                'distance' => $result['result']['delivery_distance_meter'] * 100,//配送距离
                                'order_no' => $result['result']['sf_order_id'] //顺丰订单号（标准默认为int，可以设置为string）
                            ];
                        }else{
                            $this->error = $sf->getError();
                            return false; 
                        }
                    }
                    if($company == 'dada'){
                        $dada = new Delivery('dada',$this);
                        if($pre = $dada->preOrder()){
                            $webdelivery = Setting::getItem('webdelivery',0);//获取配送设置
                            //如果是余额支付配送费
                            if($webdelivery['dada']['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['dada']['result']['fee']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['dada']['result']['fee']];
                                    $user->pay = ['inc', $pre['dada']['result']['fee']];//增加消费金额
		                            $user->score = ['inc', $pre['dada']['result']['fee']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['dada']['result']['fee'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            if($result = $dada->addOrder(['delivery_no' => $pre['dada']['result']['deliveryNo']])){
                                $dev = [
                                    'price' => $pre['dada']['result']['fee'], //配送费
                                    'distance' => (int)$pre['dada']['result']['distance'],//配送距离
                                    'order_no' => $this->order_no //商家单号
                                    //'order_no' => $pre['dada']['result']['deliveryNo'] //达达单号
                                ];
                            }else{
                                $this->error = $dada->getError();
                                return false;
                            }
                        }else{
                            $this->error = $dada->getError();
                            return false; 
                        } 
                    }
                    if($company == 'uu'){
                        $uu = new Delivery('uu',$this);
                        if($pre = $uu->preOrder()){
                            $webdelivery = Setting::getItem('webdelivery',0);//获取配送设置
                            //如果是余额支付配送费
                            if($webdelivery['uu']['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['uu']['need_paymoney']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['uu']['need_paymoney']];
                                    $user->pay = ['inc', $pre['uu']['need_paymoney']];//增加消费金额
		                            $user->score = ['inc', $pre['uu']['need_paymoney']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['uu']['need_paymoney'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            if($result = $uu->addOrder($pre['uu'])){
                                $dev = [
                                    'price' => $pre['uu']['need_paymoney'], //配送费
                                    'distance' => $pre['uu']['distance'],  //配送距离
                                    'order_no' => $result['ordercode']
                                ];
                            }else{
                                $this->error = $uu->getError();
                                return false;
                            }
                        }else{
                            $this->error = $uu->getError();
                            return false;
                        } 
                    }
                    if($company == 'make'){
                        $make = new Delivery('make',$this);
                        if($pre = $make->preOrder()){
                            $webdelivery = Setting::getItem('webdelivery',0);//获取配送设置
                            //如果是余额支付配送费
                            if($webdelivery['make']['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['make']['data']['total_price']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['make']['data']['total_price']];
                                    $user->pay = ['inc', $pre['make']['data']['total_price']];//增加消费金额
    		                        $user->score = ['inc', $pre['make']['data']['total_price']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['make']['data']['total_price'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            if($result = $make->addOrder($pre['make'])){
                                $dev = [
                                    'price' => $pre['make']['data']['total_price'], //配送费
                                    'distance' => $pre['make']['data']['distance'] * 1000,//配送距离
                                    'order_no' => $result['data']['order_number']
                                ];
                            }else{
                                $this->error = $make->getError();
                                return false;
                            }
                        }else{
                            $this->error = $make->getError();
                            return false; 
                        } 
                    }
                    $dev['company'] = $company;
                    $dev['delivery_time'] = time();
                    $dev['shop_id'] = $this->shop_id;
                    $dev['applet_id'] = $this->applet_id;
                    $this->delivery()->save($dev);
                }else{
                    //外卖配送完毕
                    $this->delivery->save([
                        'delivery_status' => 50,
                        'delivery_time' => time(),
                        'status' => 30
                    ]);
                    $data = [
                        'delivery_status' => 30
                    ];
                }
            }else{
                //判断堂食排号点餐
                if($this->order_mode['value']==10 AND !empty($this->row_no)){
                    Device::push($this->shop_id,'rows',$this->row_no);//叫号
                }
                //非外卖配送
                $data = [
                    'delivery_status' => 30
                ];
                if($this->order_mode['value'] == 10 AND $this->row_no == ''){
                    //发送模板消息，订单完成通知
                    food_post_tpl('finish',$this->order_id);
                }else{
                    //发送模板消息，取餐提醒通知
                    food_post_tpl('take',$this->order_id);
                }   
            }
            $data['delivery_time'] = time();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    
    /**
     * 确认收货 - 清台
     */
    public function receipt()
    {
        food_post_tpl('finish',$this->order_id);
        //堂食扫码释放餐桌
        if($this->table_id > 0){
            Table::where(['table_id' => $this->table_id])->update(['status' => 10]);
        }
        //账单分账
        $payment = Setting::getItem('payment',$this->applet_id);
        $wxpay = new WxPay($payment['wx']);
        $wxpay->divide($this);//进行分账
        return $this->save([
            'receipt_status' => 20,
            'receipt_time' => time(),
            'order_status' => 30
        ]);
    }
    
    /**
     * 取消已经推送的外卖订单
     */
    public function cancelDelivery()
    {
        $data = [
            'shop_status' => 20,
            'shop_time' => time(),
            'delivery_status' => 10,
            'delivery_time' => 10
        ];
        if($this->delivery['company']['value'] != 'self'){
            $dv = new Delivery($this->delivery['company']['value'],$this);
            if(!$result = $dv->cancelOrder($this->delivery['order_no'])){
                $this->error = $dv->getError();
                return false;
            }
        }
         // 开启事务
        Db::startTrans();
        try {
            //退款 --- 待补充
            OrderDelivery::where('order_delivery_id',$this->delivery['order_delivery_id'])->delete();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 退款处理
     */
    public function refund($is_refund = 0)
    {
        if($this->refund_price > $this->pay_price){
            $this->error = '退款金额不可大于实付金额';
            return false;
        }
        //同意退款
        if($is_refund==1){
            // 开启事务
            Db::startTrans();
            try {
                //判断支付方式
                if(empty($this->transaction_id)){
                    //余额变动
                    $user = User::getUser(['user_id' => $this->user_id]);
                    $user->money = ['inc',$this->refund_price];//返回余额
                    if($this->refund_price > $user->pay){
                        $pay = $user->pay;
                    }else{
                        $pay = $this->refund_price;
                    }
                    $user->pay = ['dec', $pay];//扣减消费金额
                    if($this->refund_price > $user->score){
                        $score = $user->score;
                    }else{
                        $score = $this->refund_price;
                    }
                    $user->score = ['dec', $score];//扣减积分
                    $user->save();
                    //添加交易记录
                    $record = new Record;
                    $record->save([
                        'order_no' => $this['order_no'],
                        'money' => $this['refund_price'],
                        'user_id' => $this['user_id'],
                        'shop_id' => $this['shop_id'],
                        'applet_id' => $this['applet_id'],
                        'action' => 60,//退款
                        'remark' => '订单退款'
                    ]);
                    //更新商品库存、销量
                    $this->save([
                        'refund_status' => 20,
                        'refund_time' => time()
                    ]);
                    //发送退款申请状态提醒订阅消息
                    food_post_tpl('refund',$this->order_id);
                }else{
                    //微信退款处理
                    $values = Setting::getItem('payment');
                    $WxPay = new WxPay($values['wx']);
                    $result = $WxPay->refund($this->order_no,$this->transaction_id,$this->pay_price,$this->refund_price,$this->refund_desc);
                    if($result){
                        $this->error = $result;
                        return false;
                    }
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
            }
            return false;
        }
        //拒绝退款
        // 开启事务
        Db::startTrans();
        try {
            OrderGoods::where('order_id',$this->order_id)->update([
                'refund_num' => 0,
                'refund_price' => 0
            ]);
            $this->save([
                'order_status' => 10,
                'refund_status' => 10,
                'refund_price' => 0
            ]);
            //发送退款申请状态提醒订阅消息
            food_post_tpl('refund',$this->order_id);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 清除订单记录
     */
    public function remove($order_id)
    {
        $filter['order_id'] = $order_id;
        // 开启事务
        Db::startTrans();
        try {
            $this->withoutGlobalScope()->where($filter)->delete();
            OrderAddress::withoutGlobalScope()->where($filter)->delete();
            OrderDelivery::withoutGlobalScope()->where($filter)->delete();
            OrderGoods::withoutGlobalScope()->where($filter)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    /**
     * 获取订单分类统计
     */
    public function getOrderClassCount($dataType='all',$shop_id='',$user_id='')
    {
        // 筛选条件
        $filter = [];
        !empty($shop_id) && $filter['shop_id'] = $shop_id;
        !empty($user_id) && $filter['user_id'] = $user_id;
        !empty($user_id) && $filter['user_id'] = $user_id;
        $model = $this->order(['order_id' => 'desc']);
        // 订单数据类型
        switch ((string)$dataType) {
            case 'all'; //全部
                break;
            case 'payment'; //待付款
                $filter['pay_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'collection'; //待收款
                $filter['pay_status'] = 30;
                $filter['order_status'] = 10;
                break;
            case 'shop';//待接单
                $model->where('pay_status','>',10);
                $filter['order_status'] = 10;
                $filter['shop_status'] = 10;
                break;
            case 'delivery';//待配送
                $model->where('shop_status','>',10);
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 10;
                break;
            case 'receipt';//待收货
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 30;
                $filter['receipt_status'] = 10;
                break;
            case 'cancel';//被取消
                $filter['order_status'] = 20;
                break;
            case 'complete';//已完成
                $filter['order_status'] = 30;
                break;
            case 'comment';//待评价
                $filter['is_cmt'] = 0;
                $filter['order_status'] = 30;
                break;
            case 'refund';//全部退款
                $filter['order_status'] = 40;
                break;
            case 'refund10';//待退款
                $filter['refund_status'] = 10;
                $filter['order_status'] = 40;
                break;
            case 'refund20';//已退款
                $filter['refund_status'] = 20;
                $filter['order_status'] = 40;
                break;
        }
        return $model->where($filter)->count();
    }

    /**
     * 根据时间段统计数量
     */
    public static function getDateCount($shop)
    {
        $self = new static;
         // 筛选条件
        $filter = [];
        $shop['shop_id'] > 0 && $filter['shop_id'] = $shop['shop_id'];
        $applet_id = $self::$applet_id;
        $applet_id > 0 && $filter['applet_id'] = $applet_id;
        $count = array();
        $count['count'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->count();
        $count['tang'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode'=>10])->count();
        $count['qu'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode' =>30])->count();
        $count['wai'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode' =>20])->count();
        $count['refund'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_status' => 40])->count();
        return $count;
    }

    /**
     * 根据条件统计数量
     */
    public static function getCount($shop_id = 0)
    {
        $self = new static;
        // 筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        $applet_id = $self::$applet_id;
        empty($applet_id) && $filter['applet_id'] = 0;
        $count = array();
        $count[0]['count'] = self::where($filter)->count();//全部
        $count[0]['refund'] = self::where($filter)->where(['order_status' => 40,'refund_status'=>10])->count();//待退款
        //今天
        $star = strtotime(date('Y-m-d 00:00:00',time()));
        $count[1]['count'] = self::where($filter)->where('create_time','>',$star)->count();
        $count[1]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->count();
        $count[1]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->count();
        $count[1]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->count();
        $count[1]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->count();
        //昨天
        $star = strtotime("-1 day");
        $end = strtotime(date('Y-m-d 00:00:00',time()));
        $count[2]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //前天
        $star = strtotime("-2 day");
        $end = strtotime("-1 day");
        $count[3]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-4天
        $star = strtotime("-3 day");
        $end = strtotime("-2 day");
        $count[4]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-5天
        $star = strtotime("-4 day");
        $end = strtotime("-3 day");
        $count[5]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-6天
        $star = strtotime("-5 day");
        $end = strtotime("-4 day");
        $count[6]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-7天
        $star = strtotime("-6 day");
        $end = strtotime("-5 day");
        $count[7]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //本月起至时间 - 月度统计 
        $end = mktime(0,0,0,date('m'),1,date('y')); 
        $count[8]['count'] = self::where($filter)->where('create_time','>',$end)->count();
        $count[8]['tang'] =self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$end)->count();
        $count[8]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$end)->count();
        $count[8]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$end)->count();
        $count[8]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$end)->count();
        //上月开始  
        $star = mktime(0,0,0,date('m')-1,1,date('y')); 
        $count[9]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        return $count;
    }

}
